package org.abluedog.ssfb.pdc;

import org.bukkit.persistence.PersistentDataAdapterContext;
import org.bukkit.persistence.PersistentDataType;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;
import java.nio.ByteBuffer;

public class BodyCompositionPDC implements PersistentDataType<byte[], BodyComposition> {
    @NotNull
    @Override
    public Class<byte[]> getPrimitiveType() {
        return byte[].class;
    }

    @NotNull
    @Override
    public Class<BodyComposition> getComplexType() {
        return BodyComposition.class;
    }

    @NotNull
    @Override
    public byte[] toPrimitive(@NotNull BodyComposition complex, @NotNull PersistentDataAdapterContext context) {
        Class<BodyComposition> bodyCompositionClass = BodyComposition.class;
        Field[] fields = bodyCompositionClass.getDeclaredFields();
        ByteBuffer bb = ByteBuffer.allocate(Double.BYTES * fields.length);
        bb.putDouble(complex.getAge());
        bb.putDouble(complex.getHeight());
        bb.putDouble(complex.getWeight());
        bb.putDouble(complex.getBmr());
        bb.putDouble(complex.getProteinMass());
        bb.putDouble(complex.getMuscleMass());
        bb.putDouble(complex.getFatMass());
        bb.putDouble(complex.getWaterMass());
        return bb.array();
    }

    @NotNull
    @Override
    public BodyComposition fromPrimitive(@NotNull byte[] primitive, @NotNull PersistentDataAdapterContext context) {
        ByteBuffer bb = ByteBuffer.wrap(primitive);
        double age = bb.getDouble();
        double height = bb.getDouble();
        double weight = bb.getDouble();
        double bmr = bb.getDouble();
        double protein = bb.getDouble();
        double muscle = bb.getDouble();
        double fat = bb.getDouble();
        double water = bb.getDouble();
        return new BodyComposition(age, height, weight, bmr, protein, muscle, fat, water);
    }
}
